﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.IO;

namespace Moon.Sql
{
    public class MySqlCodeFirst : ICodeFirst
    {
        private IDatabase Database;
        public MySqlCodeFirst(IDatabase _Database)
        {
            Database = _Database;
        }

        public string Build<T>()
        {
            var table = ClassMapper.Mapping<T>();
            var tableName = table.TableName;
            StringBuilder builder = new StringBuilder();
            builder.Append($"create table `{tableName}`(");
            foreach (var item in table.Properties)
            {
                if (item.Ignored) continue;
                builder.AppendLine($"{GetColumn(item)},");
            }
            return builder.ToString().TrimEnd(",\r\n".ToArray()) + ")";
        }

        private string GetColumn(PropertyMap property)
        {
            string column = $"`{property.ColumnName}`";
            Type type = property.PropertyInfo.PropertyType;
            Dictionary<Type, string> hash = new Dictionary<Type, string>()
            {
                { typeof(bool), "bit(1)"},
                { typeof(bool?), "bit(1)"},
                { typeof(sbyte), "tinyint(3)"},
                { typeof(sbyte?), "tinyint(3)"},
                { typeof(short), "smallint(6)"},
                { typeof(short?), "smallint(6)"},
                { typeof(int), "int(11)"},
                { typeof(int?), "int(11)"},
                { typeof(long), "bigint(20)"},
                { typeof(long?), "bigint(20)"},
                { typeof(byte), "tinyint(3)"},
                { typeof(byte?), "tinyint(3)"},
                { typeof(ushort), "smallint(5)"},
                { typeof(ushort?), "smallint(5)"},
                { typeof(uint), "int(10)"},
                { typeof(uint?), "int(10)"},
                { typeof(ulong), "bigint(20)"},
                { typeof(ulong?), "bigint(20)"},
                { typeof(double), "double"},
                { typeof(double?), "double"},
                { typeof(float), "float"},
                { typeof(float?), "float"},
                { typeof(decimal), "decimal(10,2)"},
                { typeof(decimal?), "decimal(10,2)"},
                { typeof(DateTime), "datetime"},
                { typeof(DateTime?), "datetime"},
                { typeof(string), $"varchar({property.ColumnSize ?? 255})"},
                { typeof(char), "char(1)"},
            };
            column += " " + hash[type];
            if (property.IsIdentity)
            {
                column += $" auto_increment";
            }
            if (property.IsPrimaryKey)
            {
                column += $" primary key";
            }
            return column;
        }
    }
}